<?php
namespace app\api\controller;
use app\common\controller\CommonApi;
use Pay\Pay;
/**
 * 用户定位相关操作接口
 * date：2019-06-11
 */
class UserPosition extends CommonApi{
    protected $tn = 'user_position';


    //定位列表
    public function positions(){
        $list = db($this->tn)->where('user_id',UID)->order('id asc')->limit(($this->p-1)*config('page_size'),config('page_size'))->select();
        $this->apiReturn(1,'列表',$list);
    }

 

    //删除定位
    public function delPosition(){
        if(!isset($this->post['id']) || intval($this->post['id']) < 1){
            $this->apiReturn(0,'参数id丢失');
        }
        $info = model('common/user_position')->where('id',intval($this->post['id']))->where('user_id',UID)->find();
        if(is_null($info)){
            $this->apiReturn(0,'该定位不存在或已被删除');
        }
        if($info['default'] == 1){
            $this->apiReturn(0,'默认定位不可删除');
        }
        if(!$info->delete()){
            $this->apiReturn(0,'删除失败，请稍后再试');
        }
        $this->apiReturn(1,'删除成功');
    }


    //编辑定位
    public function editPosition(){
        $validate = new \think\validate([
            'lng' => 'require',
            'lat' => 'require',
            'city' => 'require'
        ],[
            'lng.require' => '参数lng丢失',
            'lat.require' => '参数lat丢失',
            'city.require' => '参数city丢失'
        ]);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $model = model($this->tn);
        if(isset($this->post['id']) && intval($this->post['id']) > 0){
            $model = $model->where('user_id',UID)->where('id',intval($this->post['id']))->find();

            if(is_null($model)){
                $this->apiReturn(0,'该定位不存在或已被删除');
            }

            $this->post['default'] = $model['default'];
            unset($this->post['id']);
        }else{
            $count = db($this->tn)->where('user_id',UID)->count();
            if($count >= $this->user_info['grade']+1+$this->user_info['position_num']){
                $this->apiReturn(0,'定位达到上限');
            }
            if($count == 0){
            
                $this->post['default'] = 1;
            }

        }

        db()->startTrans();
        
        if(isset($this->post['default']) && $this->post['default'] == 1){
            if(!model('common/user')->save([
                'from_lng' => trim($this->post['lng']),
                'from_lat' => trim($this->post['lat']),
                'from_city' => trim($this->post['city'])
                ],['id' => UID])){
                db()->rollback();
                $this->apiReturn(0,'修改会员信息失败');
            }

        }
        $this->post['user_id'] = UID;
        if(!$model->allowField(true)->save($this->post)){
            db()->rollback();
            $this->apiReturn(0,'修改失败，请稍后再试');
        }
        db()->commit();
        $this->apiReturn(1,'操作成功');
    }


    //设置默认
    public function setDefault(){
        if(!isset($this->post['id']) && intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $model = model('common/user_position')->where('user_id',UID)->where('id',intval($this->post['id']))->find();
        if(is_null($model)){
            $this->apiReturn(0,'该定位不存在或已被删除');
        }
        if($model['default'] == 1){
            $this->apiReturn(1,'设置成功');
        }
        db()->startTrans();
        if(!db('user_position')->where('user_id',UID)->where('default',1)->update(['default' => 0])){
            db()->rollback();
            $this->apiReturn(1,'修改失败，请稍后再试');
        }
        if(!$model->save(['default' => 1])){
            db()->rollback();
            $this->apiReturn(1,'修改失败，请稍后再试');
        }
        if(!model('common/user')->save([
            'from_lng' => trim($model['lng']),
            'from_lat' => trim($model['lat']),
            'from_city' => trim($model['city'])
            ],['id' => UID])){
            db()->rollback();
            $this->apiReturn(0,'修改会员信息失败');
        }
        db()->commit();
        $this->apiReturn(1,'设置成功');
    }  

    //购买定位条数
    public function buy(){
        $validate = new \think\validate([
            'num' => 'require',
            'pay_type' => 'require|in:0,1,2'
        ],[
            'num.require' => '请输入购买条数',
            'pay_type.require' => '请选择购买方式',
            'pay_type.in' => '购买方式错误'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(intval($this->post['num']) <= 0){
            $this->apiReturn(0,'请输入购买条数');
        }

        $price = db('web_config')->where('key','position_price')->value('value');

        $price *= intval($this->post['num']);

        //余额支付
        if($this->post['pay_type'] == 0){
            if($this->user_info['balance'] < $price){
                $this->apiReturn(0,'余额不足');
            }

            db()->startTrans();
            if(!db('user')->where('id',UID)->setDec('balance',$price)){
                db()->rollback();
                $this->apiReturn(0,'余额修改失败，请稍后再试');
            }
            //添加购买记录
            if(!$id = db('position_buy')->insertGetId([
                'user_id' => UID,
                'num' => intval($this->post['num']),
                'price' => $price,
                'order_no' => date('YmdHis').rand(10000,99999),
                'pay_status' => 1,
                'pay_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'添加记录失败');
            }
            
            //添加交易明细
            if(!db('bill')->insert([
                'user_id' => UID,
                'type' => 13,
                'num' => $price,
                'foreign_key' => $id,
                'add_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'购买失败，未知错误');
            }

            //消息通知
            if(!db('information')->insert([
                'user_id' => UID,
                'type' => 13,
                'content' => '购买定位-支付成功',
                'add_time' => time()
            ])){
                db()->rollback();
                $this->apiReturn(0,'购买失败，未知错误');
            }
            db()->commit();
            $this->apiReturn(1,'购买成功');
        }

        //微信支付
        if($this->post['pay_type'] == 1){
            $options = [
                'out_trade_no' => date('YmdHis').rand(10000,99999),
                'total_fee' => $price * 100,
                'body' => '购买位置',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'attach' => serialize(['attach' => 7,'user' => UID,'num' => intval($this->post['num'])])
            ];

            $pay = new Pay(config('pay'));

            try{
                $result = $pay->driver('wechat')->gateway('app')->apply($options);
                $this->apiReturn(1,'微信支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }

        }

        //支付宝支付
        if($this->post['pay_type'] == 2){
            $options = [
                'out_trade_no' => date('YmdHis').rand(10000,99999),
                'total_amount' =>  $price,
                'subject' => '购买位置',
                'passback_params' => UrlEncode(serialize(['passback_params' => 7,'user' => UID,'num' => intval($this->post['num'])]))
            ];
            $pay = new Pay(config('pay'));
            try{
                $result = $pay->driver('alipay')->gateway('app')->apply($options);
                $this->apiReturn(1,'支付宝支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
    } 
}
